package pwr.online.cow;

import java.util.Random;

import pwr.online.cow.model.Board;
import pwr.online.cow.model.Position;
import pwr.online.cow.model.Position1D;

public class CowSearchAlgorithm1D extends CowSearchAlgorithm implements BoardControllerListener {
	private int mMoveLimit;
	private int mMoveCount;
	private int nextX;
	private int startXDirection;
	private int mMoveNumber;
	private Position1D mNextPosition;
	
	public CowSearchAlgorithm1D(Board board, Position cowPosition) {
		super(board, cowPosition);
		startXDirection = 1;
		mMoveCount = 1;
		mMoveLimit = 1;
		nextX = -1;
		mMoveNumber = 1;
		mNextPosition = (Position1D)getInitialPosition();
	}

	@Override
	public Position getNewPosition() {
		mNextPosition = new Position1D(mNextPosition.getX()+nextX);
		mMoveCount++;	
		
		if (mMoveCount > mMoveLimit) {
			mMoveNumber++;
			mMoveLimit = getNewMoveLimit();
			mMoveCount = 1;
			nextX *= -1;
		}
		
		return mNextPosition;
	}
	
	private int getNewMoveLimit() {
		if (mMoveNumber == 1)
			return 1;
		else {
			int power = (int) Math.pow(2, mMoveNumber - 1);
			return power + power/2;
		}
	}

	@Override
	public Position getInitialPosition() {
		return new Position1D(Board1DView.CELLS_HORIZONTAL/2);
	}

	@Override
	public void reset() {
		mMoveCount = 1;
		mMoveLimit = 1;
		mMoveNumber = 1;
		nextX = startXDirection;
		mNextPosition = (Position1D)getInitialPosition();
		mBoard.addHistoryEntry(getInitialPosition());
	}

	@Override
	public void HistoryViewChanged(int newValue) {}

	@Override
	public void RestartAlgorithm() {}

	@Override
	public void NewStartDirection(int x, int y) {
		if (x == 0) {
			Random r = new Random();
			
			x = r.nextInt(2);
			if (x == 0)
				x = -1;
		}
		
		startXDirection = x;
	}

}
